
from protocol.IPacket import *
from net.conn import *
from net.packetVec import *
import time

'''
HALL	0
TABLE	1
'''
class user():
	def __init__(self, uid, name = "default", sex = 'm', gift = 0, icon = ""):
		self.conn = packetVec("27.131.146.4", 9010)
		self.uid = uid
		self.name = name
		self.sex = sex
		self.gift = gift
		self.icon = icon

		self.status = 0
		self.errorCode = 0

		self.cm = None

		self.tid = 0
		self.seatid = -1

	def D_print(self):
		print self.uid, self.name, self.sex, self.gift, self.status, self.tid

	def _loginPacket(self, tid):
		#self.conn.setActionStatus(0)
		output = ESOutputPacket(0x1001)
		output.writeInt(tid)
		output.writeInt(self.uid)
		output.writeString("*^&CoalaaKey#@*%")
		output.writeString(self.icon)
		output.writeInt(self.gift)
		output.end()
		self.conn.send(output.bufferx())
		time.sleep(1)
		input = self.conn.getPacket([0x2001, 0x2002])
		cmd = input.getPacketCmd()
		print "%x" % cmd
		ret = 0
		if( cmd == 0x2001 ):
			self.status = 1
			self.tid = tid
			self.D_print();
		if( cmd == 0x2002 ):
			self.errorCode = input.getShort()
			ret = -1
		#self.conn.setActionStatus(1)
		return 0

	def _sendProxyConn(self):
		output = ESOutputPacket(0x6001)
		output.begin(0x6001)
		output.writeString("127.0.0.1")
		output.writeInt(9003)
		output.end()
		self.conn.send(output.bufferx())
	
	def _sitPacket(self, seatid, buyMoney):
		#self.conn.setActionStatus(0)
		output = ESOutputPacket(0x1001)
		output.begin(0x1003)
		output.writeByte(seatid)
		output.writeInt64(buyMoney)
		output.end()
		self.conn.send(output.bufferx())
		time.sleep(1)
		input = self.conn.getPacket([0x2004, 0x2005])
		cmd = input.getPacketCmd()
		if cmd == 0x2005:
			self.seatid = seatid
		else:
			print "sit error", 0xffff & input.readShort()
		print "%x" % cmd

		
	def setCM(self, cm):
		self.cm = cm

	def login(self, tid):
		#self.conn.connect("27.131.146.4", 9010)
		self._sendProxyConn()
		self._loginPacket(tid)

	def sit(self, seatid):
		seatid = seatid - 1
		self._sitPacket(seatid, 20000)

	def processAction(self, input):
		cmd = input.getPacketCmd()
		if cmd == 0x2007:
			print "Game Start"
			return 0
		if cmd == 0x200C:
			seatid = input.readByte()
			print "web:%d, program:%d" % (seatid, self.seatid)
			if seatid != self.seatid :
				return 
			print "chip in"
			need = input.readInt64()
			raiseMin = input.readInt64()
			raiseMax = input.readInt64()

			output = ESOutputPacket(0x1004)
			type = 1
			if need == 0:
				type = 2
				chipMoney = 0
			else:
				type = 1
				chipMoney = 0
			output.writeByte(type)
			output.writeInt64(chipMoney)
			output.end()
			self.conn.send(output.bufferx())
			#call



